var cssIndex;
var clan;
var cssInitColor;
var cssInitClan;

window.onload = function() {
	clan = document.getElementById('gauche').childNodes[1].childNodes[1].innerText;	
	loadInitCss();
	var lstColor = document.getElementsByTagName('INPUT');
	var initBtn = function(event){
		resetCss(event.target)
	}
	var appliquerEvent = function(event) {
		changeColor(event);
	}

	document.getElementById('btnReset').addEventListener('click', initBtn, false);
	document.getElementById('btnResetClan').addEventListener('click', initBtn, false);
	for (i=0; i < lstColor.length; i++) {
		if (lstColor[i].type == "color") {
			lstColor[i].addEventListener('change', appliquerEvent,false);
		}
	}
	initColor('color.css') 
	initColor(clan+'.css');
}

function loadInitCss() {
	checkCss('color.css');
	cssInitColor = document.styleSheets[cssIndex];
	cssIndex = null;
	checkCss(clan+'.css');
	if (cssIndex != null) {
		cssInitClan = document.styleSheets[cssIndex];
		cssIndex = null;
	}
	else {
		document.getElementById('btnResetClan').style.display = 'none';
	}
}

function checkCss(cssName) {
	for(css = 0; css < document.styleSheets.length; css++) {
		if (document.styleSheets[css].href != null){
			hrefCss = document.styleSheets[css].href.substr(document.styleSheets[css].href.lastIndexOf('/')+1);
			if (hrefCss === cssName) {
				cssIndex = css;
			}
		}
	}
}

function initColor(cssName) {
	checkCss(cssName);

	var lstColor = document.getElementsByTagName('INPUT');
	
	for (i=0; i < lstColor.length; i++) {
		if (lstColor[i].type == "color") {
			lstColor[i].value = setDefaultColor(lstColor[i].id.substr(1));
		}
	}
}

function setDefaultColor(cssRule) {
	var property = document.styleSheets[cssIndex].rules[cssRule].style[0];	
	var color = document.styleSheets[cssIndex].rules[cssRule].style.getPropertyValue(property);
	HexColor = rgbToHex(color);
	return HexColor;
}

function changeColor(event) {
	var cible = event.target.id;	
	var cssRule = cible.substr(1);
	switch (cible.substr(0,1)) {
	case 'c':
		var property = 'color';
		break;
	case 'b':
		var property = 'background-color';
		break;
	case 't':
		var property = 'border-color';
		break;
	}
	var color = event.target.value;
	document.styleSheets[cssIndex].rules[cssRule].style.setProperty(property, color);
}

function rgbToHex(cssColor){
	var Colors = cssColor.substr(4).substr(0);
	Colors = Colors.substr(0, Colors.length-1);
	var color = Colors.split(',');
	var decColor = '#';
	for (j = 0; j < 3; j++){
		var octet = Number(color[j]).toString(16);
		if (octet.length == 1) {
			octet = 0+octet;
		}
		decColor+=octet;
	}
	return decColor;
}

function resetCss(target) {
	cssName = 'color.css';
	if (target.id == 'btnResetClan') {
		cssName = clan+'.css';
	}
	initColor(cssName);
}